<template>
  <view class="menu-container">
    <!-- 顶部操作栏 -->
    <view class="action-bar">
      <view class="search-box">
        <input type="text" placeholder="搜索菜品" v-model="searchKeyword" />
        <text class="search-icon">🔍</text>
      </view>
      <button class="add-button" @click="openAddPopup">添加菜品</button>
    </view>

    <!-- 分类标签 -->
    <scroll-view scroll-x class="category-tabs">
      <view 
        class="tab-item" 
        :class="{ active: activeCategory === category.dtId }"
        v-for="category in categories" 
        :key="category.dtId"
        @click="activeCategory = category.dtId"
      >
        {{ category.dtName }}
        <text v-if="category.dtId !== 0" class="dish-count">({{ category.dishCount }})</text>
      </view>
    </scroll-view>

    <!-- 菜品列表 -->
    <scroll-view scroll-y class="dish-list">
      <view v-if="loading" class="loading-tip">
        <text>加载中...</text>
      </view>
      <template v-else>
        <view v-if="filteredDishes.length === 0" class="empty-tip">
          <text>暂无菜品数据</text>
        </view>
        <view v-else class="dish-item" v-for="dish in filteredDishes" :key="dish.dishId">
          <image class="dish-image" :src="getImageUrl(dish.dishImage)" mode="aspectFill"></image>
          <view class="dish-info">
            <view class="dish-header">
              <text class="dish-name">{{ dish.dishName }}</text>
              <text class="dish-status" :class="{ 'status-off': dish.dishStatus !== 0 }">
                {{ dish.dishStatus === 0 ? '在售' : dish.dishStatus === 1 ? '售空' : '已下架' }}
              </text>
            </view>
            <text class="dish-desc">{{ dish.dishDescribe }}</text>
            <view class="dish-footer">
              <text class="dish-price">¥{{ dish.price.toFixed(2) }}</text>
              <view class="dish-actions">
                <button class="action-btn edit" @click="editDish(dish)">编辑</button>
                <button class="action-btn" :class="dish.dishStatus === 0 ? 'off' : 'on'" @click="toggleStatus(dish)">
                  {{ dish.dishStatus === 0 ? '下架' : '上架' }}
                </button>
              </view>
            </view>
          </view>
        </view>
      </template>
    </scroll-view>

    <!-- 添加菜品弹窗 -->
    <uni-popup ref="addPopup" type="center">
      <view class="popup-content">
        <view class="popup-header">
          <text class="popup-title">添加菜品</text>
          <text class="close-btn" @click="closeAddPopup">×</text>
        </view>
        
        <view class="popup-body">
          <view class="form-item">
            <text class="label">菜品名称</text>
            <input type="text" v-model="addForm.dishName" placeholder="请输入菜品名称" />
          </view>
          
          <view class="form-item">
            <text class="label">菜品分类</text>
            <picker @change="handleCategoryChange" :value="categoryIndex" :range="categories" range-key="dtName">
              <view class="picker">
                {{ categories[categoryIndex]?.dtName || '请选择分类' }}
              </view>
            </picker>
          </view>

          <view class="form-item">
            <text class="label">菜品价格</text>
            <input type="digit" v-model="addForm.price" placeholder="请输入菜品价格" />
          </view>

          <view class="form-item">
            <text class="label">菜品描述</text>
            <textarea v-model="addForm.dishDescribe" placeholder="请输入菜品描述" />
          </view>

          <view class="form-item">
            <text class="label">菜品图片</text>
            <view class="image-upload" @click="chooseImage">
              <image v-if="addForm.dishImage" :src="getImageUrl(addForm.dishImage)" mode="aspectFill"></image>
              <view v-else class="upload-placeholder">
                <text class="upload-icon">+</text>
                <text>上传图片</text>
              </view>
            </view>
          </view>
        </view>

        <view class="popup-footer">
          <button class="cancel-btn" @click="closeAddPopup">取消</button>
          <button class="submit-btn" @click="handleAddSubmit" :loading="submitting">保存</button>
        </view>
      </view>
    </uni-popup>

    <!-- 编辑菜品弹窗 -->
    <uni-popup ref="editPopup" type="center">
      <view class="popup-content">
        <view class="popup-header">
          <text class="popup-title">编辑菜品</text>
          <text class="close-btn" @click="closeEditPopup">×</text>
        </view>
        
        <view class="popup-body">
          <view class="form-item">
            <text class="label">菜品名称</text>
            <input type="text" v-model="editForm.dishName" placeholder="请输入菜品名称" />
          </view>
          
          <view class="form-item">
            <text class="label">菜品分类</text>
            <picker @change="handleEditCategoryChange" :value="editCategoryIndex" :range="categories" range-key="dtName">
              <view class="picker">
                {{ categories[editCategoryIndex]?.dtName || '请选择分类' }}
              </view>
            </picker>
          </view>

          <view class="form-item">
            <text class="label">菜品价格</text>
            <input type="digit" v-model="editForm.price" placeholder="请输入菜品价格" />
          </view>

          <view class="form-item">
            <text class="label">菜品描述</text>
            <textarea v-model="editForm.dishDescribe" placeholder="请输入菜品描述" />
          </view>
        </view>

        <view class="popup-footer">
          <button class="cancel-btn" @click="closeEditPopup">取消</button>
          <button class="submit-btn" @click="handleEditSubmit" :loading="submitting">保存</button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import { dishApi } from '../../utils/api.js'

export default {
  data() {
    return {
      searchKeyword: '',
      activeCategory: 0,
      categories: [
        { id: 0, name: '全部' }
      ],
      dishes: [],
      loading: false,
      addForm: {
        dishName: '',
        dtId: '',
        price: '',
        dishDescribe: '',
        dishImage: '',
        dishStatus: 1
      },
      categoryIndex: 0,
      submitting: false,
      editForm: {
        dishId: null,
        dishName: '',
        dtId: '',
        price: '',
        dishDescribe: '',
        dishStatus: 1
      },
      editCategoryIndex: 0
    }
  },

  onLoad() {
    this.loadData()
  },

  onShow() {
    // 每次页面显示时重新加载数据
    this.loadData()
  },

  computed: {
    filteredDishes() {
      let filtered = this.dishes;
      
      // 按分类筛选
      if (this.activeCategory !== 0) {
        filtered = filtered.filter(dish => dish.dtId === this.activeCategory);
      }
      
      // 按关键词搜索
      if (this.searchKeyword) {
        const keyword = this.searchKeyword.toLowerCase();
        filtered = filtered.filter(dish => 
          dish.dishName.toLowerCase().includes(keyword) ||
          dish.dishDescribe.toLowerCase().includes(keyword)
        );
      }
      
      return filtered;
    }
  },

  methods: {
    // 加载数据
    async loadData() {
      try {
        this.loading = true
        const [typesRes, dishesRes] = await Promise.all([
          dishApi.getDishTypes(),
          dishApi.getAllDishes()
        ])

        if (typesRes.code === 200 && dishesRes.code === 200) {
          // 初始化分类数据，确保每个分类都有 dishCount 属性
          this.categories = [
            { dtId: 0, dtName: '全部', dishCount: 0 },
            ...typesRes.data.map(type => ({
              ...type,
              dishCount: 0  // 确保每个分类都有 dishCount 属性
            }))
          ]

          // 直接使用原始数据
          this.dishes = dishesRes.data

          // 统计每个分类下的菜品数量
          this.dishes.forEach(dish => {
            const category = this.categories.find(c => c.dtId === dish.dtId)
            if (category) {
              category.dishCount = (category.dishCount || 0) + 1
            }
          })

          // 设置"全部"分类的菜品数量
          this.categories[0].dishCount = this.dishes.length
        } else {
          throw new Error('获取数据失败')
        }
      } catch (error) {
        console.error('加载数据失败:', error)
        uni.showToast({
          title: error.message || '加载失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },

    navigateTo(url) {
      uni.navigateTo({
        url: url
      })
    },

    editDish(dish) {
      this.openEditPopup(dish)
    },

    async toggleStatus(dish) {
      try {
        // SELL(0) - 出售, SOLD_OUT(1) - 售空, TAKEN_OFF_THE_SHELVES(2) - 下架
        // 当前是出售状态(0)时，改为下架(2)；当前是下架状态(2)时，改为出售(0)
        const newStatus = dish.dishStatus === 0 ? 2 : 0
        const res = await dishApi.updateDishStatus(dish.dishId, newStatus)
        
        if (res.code === 200) {
          dish.dishStatus = newStatus
          uni.showToast({
            title: newStatus === 0 ? '上架成功' : '下架成功',
            icon: 'success'
          })
        } else {
          throw new Error(res.msg || '操作失败')
        }
      } catch (error) {
        console.error('更新菜品状态失败:', error)
        uni.showToast({
          title: error.message || '操作失败',
          icon: 'none'
        })
      }
    },

    // 打开添加弹窗
    openAddPopup() {
      this.$refs.addPopup.open()
      // 重置表单
      this.addForm = {
        dishName: '',
        dtId: '',
        price: '',
        dishDescribe: '',
        dishImage: '',
        dishStatus: 1
      }
      this.categoryIndex = 0
    },

    // 关闭添加弹窗
    closeAddPopup() {
      this.$refs.addPopup.close()
    },

    // 处理分类选择
    handleCategoryChange(e) {
      this.categoryIndex = e.detail.value
      this.addForm.dtId = this.categories[this.categoryIndex].dtId
    },

    // 选择图片
    async chooseImage() {
      try {
        const res = await uni.chooseImage({
          count: 1,
          sizeType: ['compressed'],
          sourceType: ['album', 'camera']
        })
        
        if (res.tempFilePaths && res.tempFilePaths[0]) {
          // 这里应该先上传图片到服务器，获取图片URL
          // 暂时使用本地路径
          this.addForm.dishImage = res.tempFilePaths[0]
        }
      } catch (error) {
        console.error('选择图片失败:', error)
      }
    },

    // 提交添加
    async handleAddSubmit() {
      // 表单验证
      if (!this.addForm.dishName) {
        return uni.showToast({
          title: '请输入菜品名称',
          icon: 'none'
        })
      }
      if (!this.addForm.dtId) {
        return uni.showToast({
          title: '请选择菜品分类',
          icon: 'none'
        })
      }
      if (!this.addForm.price) {
        return uni.showToast({
          title: '请输入菜品价格',
          icon: 'none'
        })
      }
      if (!this.addForm.dishDescribe) {
        return uni.showToast({
          title: '请输入菜品描述',
          icon: 'none'
        })
      }

      try {
        this.submitting = true
        
        // 转换价格为数字
        const submitData = {
          ...this.addForm,
          price: parseFloat(this.addForm.price)
        }

        const res = await dishApi.createDish(submitData)
        
        if (res.code === 200) {
          uni.showToast({
            title: '添加成功',
            icon: 'success'
          })
          this.closeAddPopup()
          this.loadData() // 刷新列表
        } else {
          throw new Error(res.msg || '添加失败')
        }
      } catch (error) {
        uni.showToast({
          title: error.message || '添加失败',
          icon: 'none'
        })
      } finally {
        this.submitting = false
      }
    },

    // 打开编辑弹窗
    openEditPopup(dish) {
      this.editForm = {
        dishId: dish.dishId,
        dishName: dish.dishName,
        dtId: dish.dtId,
        price: dish.price.toString(),
        dishDescribe: dish.dishDescribe,
        dishStatus: dish.dishStatus
      }
      // 找到当前分类的索引
      this.editCategoryIndex = this.categories.findIndex(c => c.dtId === dish.dtId)
      this.$refs.editPopup.open()
    },

    // 关闭编辑弹窗
    closeEditPopup() {
      this.$refs.editPopup.close()
    },

    // 处理编辑分类选择
    handleEditCategoryChange(e) {
      this.editCategoryIndex = e.detail.value
      this.editForm.dtId = this.categories[this.editCategoryIndex].dtId
    },

    // 提交编辑
    async handleEditSubmit() {
      // 表单验证
      if (!this.editForm.dishName) {
        return uni.showToast({
          title: '请输入菜品名称',
          icon: 'none'
        })
      }
      if (!this.editForm.dtId) {
        return uni.showToast({
          title: '请选择菜品分类',
          icon: 'none'
        })
      }
      if (!this.editForm.price) {
        return uni.showToast({
          title: '请输入菜品价格',
          icon: 'none'
        })
      }
      if (!this.editForm.dishDescribe) {
        return uni.showToast({
          title: '请输入菜品描述',
          icon: 'none'
        })
      }

      try {
        this.submitting = true
        
        // 转换价格为数字
        const submitData = {
          ...this.editForm,
          price: parseFloat(this.editForm.price)
        }

        const res = await dishApi.updateDish(this.editForm.dishId, submitData)
        
        if (res.code === 200) {
          uni.showToast({
            title: '修改成功',
            icon: 'success'
          })
          this.closeEditPopup()
          this.loadData() // 刷新列表
        } else {
          throw new Error(res.msg || '修改失败')
        }
      } catch (error) {
        uni.showToast({
          title: error.message || '修改失败',
          icon: 'none'
        })
      } finally {
        this.submitting = false
      }
    },

    getImageUrl(imagePath) {
      if (!imagePath) {
        return '';
      }
      // 如果已经是完整的URL，直接返回
      if (imagePath.startsWith('http://') || imagePath.startsWith('https://')) {
        return imagePath;
      }
      // 添加OSS前缀
      return `https://rsl-plus.oss-rg-china-mainland.aliyuncs.com/${imagePath}`;
    }
  }
}
</script>

<style>
.menu-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.action-bar {
  padding: 20rpx;
  background-color: #ffffff;
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.search-box {
  flex: 1;
  position: relative;
}

.search-box input {
  background-color: #f5f5f5;
  height: 70rpx;
  border-radius: 35rpx;
  padding: 0 60rpx 0 30rpx;
  font-size: 28rpx;
}

.search-icon {
  position: absolute;
  right: 20rpx;
  top: 50%;
  transform: translateY(-50%);
  color: #999;
}

.add-button {
  background-color: #C70209;
  color: #ffffff;
  font-size: 28rpx;
  padding: 0 30rpx;
  height: 70rpx;
  line-height: 70rpx;
  border-radius: 35rpx;
}

.category-tabs {
  background-color: #ffffff;
  white-space: nowrap;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f5f5f5;
}

.tab-item {
  display: inline-flex;
  align-items: center;
  gap: 8rpx;
  padding: 0 30rpx;
  font-size: 28rpx;
  color: #666;
  position: relative;
}

.tab-item.active {
  color: #C70209;
  font-weight: bold;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: -20rpx;
  left: 50%;
  transform: translateX(-50%);
  width: 40rpx;
  height: 4rpx;
  background-color: #C70209;
}

.dish-count {
  font-size: 24rpx;
  color: #999;
}

.dish-list {
  flex: 1;
  padding: 20rpx;
}

.dish-item {
  background-color: #ffffff;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
  padding: 20rpx;
  display: flex;
}

.dish-image {
  width: 160rpx;
  height: 160rpx;
  border-radius: 8rpx;
  margin-right: 20rpx;
}

.dish-info {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.dish-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10rpx;
}

.dish-name {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.dish-status {
  font-size: 24rpx;
  color: #07c160;
}

.status-off {
  color: #999;
}

.dish-desc {
  font-size: 26rpx;
  color: #999;
  margin-bottom: 20rpx;
}

.dish-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: auto;
}

.dish-price {
  font-size: 32rpx;
  color: #C70209;
  font-weight: bold;
}

.dish-actions {
  display: flex;
  gap: 20rpx;
}

.action-btn {
  font-size: 24rpx;
  padding: 0 20rpx;
  height: 50rpx;
  line-height: 50rpx;
  border-radius: 25rpx;
  background-color: #f5f5f5;
  color: #666;
}

.action-btn.edit {
  background-color: #e6f7ff;
  color: #1890ff;
}

.action-btn.off {
  background-color: #fff1f0;
  color: #ff4d4f;
}

.action-btn.on {
  background-color: #f6ffed;
  color: #52c41a;
}

/* 添加新样式 */
.loading-tip {
  text-align: center;
  padding: 30rpx;
  color: #999;
  font-size: 28rpx;
}

.empty-tip {
  text-align: center;
  padding: 30rpx;
  color: #999;
  font-size: 28rpx;
}

/* 弹窗样式 */
.popup-content {
  width: 600rpx;
  background-color: #ffffff;
  border-radius: 12rpx;
  overflow: hidden;
}

.popup-header {
  padding: 30rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1rpx solid #f5f5f5;
}

.popup-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.close-btn {
  font-size: 40rpx;
  color: #999;
  padding: 0 20rpx;
}

.popup-body {
  padding: 30rpx;
  max-height: 800rpx;
  overflow-y: auto;
}

.form-item {
  margin-bottom: 30rpx;
}

.form-item:last-child {
  margin-bottom: 0;
}

.label {
  display: block;
  font-size: 28rpx;
  color: #333;
  margin-bottom: 10rpx;
}

input, .picker {
  width: 100%;
  height: 80rpx;
  background-color: #f5f5f5;
  border-radius: 8rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  box-sizing: border-box;
}

textarea {
  width: 100%;
  height: 200rpx;
  background-color: #f5f5f5;
  border-radius: 8rpx;
  padding: 20rpx;
  font-size: 28rpx;
  box-sizing: border-box;
}

.image-upload {
  width: 200rpx;
  height: 200rpx;
  background-color: #f5f5f5;
  border-radius: 8rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

.image-upload image {
  width: 100%;
  height: 100%;
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #999;
  font-size: 24rpx;
}

.upload-icon {
  font-size: 48rpx;
  margin-bottom: 10rpx;
}

.popup-footer {
  padding: 20rpx 30rpx;
  display: flex;
  gap: 20rpx;
  border-top: 1rpx solid #f5f5f5;
}

.submit-btn, .cancel-btn {
  flex: 1;
  height: 80rpx;
  line-height: 80rpx;
  text-align: center;
  border-radius: 40rpx;
  font-size: 28rpx;
}

.submit-btn {
  background-color: #C70209;
  color: #ffffff;
}

.cancel-btn {
  background-color: #f5f5f5;
  color: #666;
}
</style> 